"""
Steam Cookie拉取接口数据模型
"""
from dataclasses import dataclass, field, asdict
from typing import Dict, Any, Optional, List
import json
import logging

logger = logging.getLogger(__name__)

@dataclass
class SteamCookiePullRequest:
    """Steam Cookie拉取请求"""
    sceneCode: str
    Sessionid: str

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式
        
        Returns:
            Dict[str, Any]: 字典格式的数据
        """
        return {
            "sceneCode": self.sceneCode,
            "Sessionid": self.Sessionid
        }

@dataclass
class SteamCookieData:
    """Steam Cookie数据"""
    steamId: str
    insertTime: str
    cookieDic: Dict[str, str]
    userId: int

    @classmethod
    def from_json(cls, json_str: str) -> Optional['SteamCookieData']:
        """从JSON字符串创建Steam Cookie数据对象
        
        Args:
            json_str: JSON字符串
            
        Returns:
            Optional[SteamCookieData]: Steam Cookie数据对象，如果解析失败则返回None
        """
        try:
            data = json.loads(json_str)
            return cls(
                steamId=data.get('steamId', ''),
                insertTime=data.get('insertTime', ''),
                cookieDic=data.get('cookieDic', {}),
                userId=data.get('userId', 0)
            )
        except Exception as e:
            logger.error(f"解析Steam Cookie数据时发生错误: {str(e)}")
            return None

@dataclass
class SteamPath:
    """Steam路径配置"""
    path: str
    pathCode: str
    pathName: str

@dataclass
class SteamProxyConfig:
    """Steam代理配置"""
    enabled: float
    proxyConfig: Optional[Dict[str, Any]] = None

@dataclass
class SteamConfigs:
    """Steam配置信息"""
    steamPaths: Dict[str, SteamPath]
    steamProxy: SteamProxyConfig

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'SteamConfigs':
        """从字典创建Steam配置对象
        
        Args:
            data: 配置数据字典
            
        Returns:
            SteamConfigs: Steam配置对象
        """
        steam_paths = {}
        if data.get('steamPaths'):
            for key, path_data in data['steamPaths'].items():
                steam_paths[key] = SteamPath(
                    path=path_data.get('path', ''),
                    pathCode=path_data.get('pathCode', ''),
                    pathName=path_data.get('pathName', '')
                )
                
        steam_proxy = SteamProxyConfig(
            enabled=data.get('steamProxy', {}).get('enabled', 0.0),
            proxyConfig=data.get('steamProxy', {}).get('proxyConfig')
        )
        
        return cls(
            steamPaths=steam_paths,
            steamProxy=steam_proxy
        )

@dataclass
class SteamCookiePullData:
    """Steam Cookie拉取数据"""
    steamCookieRaw: str
    steamCookie: Optional[SteamCookieData] = None
    fullPushEnabled: int = 0
    steamConfigs: Optional[SteamConfigs] = None

@dataclass
class SteamCookiePullResponse:
    """Steam Cookie拉取响应"""
    code: int
    msg: str
    timestamp: int
    data: Optional[SteamCookiePullData] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'SteamCookiePullResponse':
        """从字典创建响应对象
        
        Args:
            data: 响应数据字典
            
        Returns:
            SteamCookiePullResponse: 响应对象
        """
        response_data = None
        if data.get('data'):
            steam_configs = None
            if data['data'].get('steamConfigs'):
                steam_configs = SteamConfigs.from_dict(data['data']['steamConfigs'])
            
            steam_cookie_raw = data['data'].get('steamCookie', '')
            steam_cookie = None
            if steam_cookie_raw:
                steam_cookie = SteamCookieData.from_json(steam_cookie_raw)
                
            response_data = SteamCookiePullData(
                steamCookieRaw=steam_cookie_raw,
                steamCookie=steam_cookie,
                fullPushEnabled=data['data'].get('fullPushEnabled', 0),
                steamConfigs=steam_configs
            )
            
        return cls(
            code=data.get('code'),
            msg=data.get('msg', ''),
            timestamp=data.get('timestamp'),
            data=response_data
        )
